// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 侧边栏切换
    const sidebarToggle = document.querySelector('#sidebarToggle');
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function(e) {
            e.preventDefault();
            document.body.classList.toggle('sidebar-toggled');
            document.querySelector('.sidebar').classList.toggle('toggled');
        });
    }

    // 关闭侧边栏（在小屏幕上）
    const width = window.innerWidth;
    if (width < 768) {
        document.querySelector('.sidebar').classList.add('toggled');
    }

    // 表单验证
    const forms = document.querySelectorAll('.needs-validation');
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });

    // 数据表格初始化
    const dataTables = document.querySelectorAll('.dataTable');
    if (dataTables.length > 0) {
        dataTables.forEach(table => {
            const searchInput = document.querySelector(`#${table.id}Search`);
            if (searchInput) {
                searchInput.addEventListener('keyup', function() {
                    const searchText = this.value.toLowerCase();
                    const rows = table.querySelectorAll('tbody tr');

                    rows.forEach(row => {
                        const text = row.textContent.toLowerCase();
                        row.style.display = text.includes(searchText) ? '' : 'none';
                    });
                });
            }
        });
    }

    // 确认删除对话框
    const deleteButtons = document.querySelectorAll('.btn-delete');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            if (!confirm('确定要删除这条记录吗？此操作不可撤销。')) {
                e.preventDefault();
            }
        });
    });

    // 显示密码切换
    const togglePasswordButtons = document.querySelectorAll('.toggle-password');
    togglePasswordButtons.forEach(button => {
        button.addEventListener('click', function() {
            const passwordField = document.querySelector(this.getAttribute('data-target'));
            const type = passwordField.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordField.setAttribute('type', type);
            this.textContent = type === 'password' ? '显示' : '隐藏';
        });
    });

    // 健康记录图表（如果存在）
    const healthChartCanvas = document.getElementById('healthChart');
    if (healthChartCanvas) {
        // 这里可以添加图表库的代码，例如Chart.js
        console.log('Health chart would be initialized here');
    }

    // 药物提醒倒计时
    const medicationTimers = document.querySelectorAll('.medication-timer');
    if (medicationTimers.length > 0) {
        medicationTimers.forEach(timer => {
            const targetTime = new Date(timer.getAttribute('data-time')).getTime();

            const updateTimer = function() {
                const now = new Date().getTime();
                const distance = targetTime - now;

                if (distance < 0) {
                    timer.innerHTML = '<span class="text-danger">现在</span>';
                    return;
                }

                const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                timer.innerHTML = `${hours}小时 ${minutes}分钟 ${seconds}秒`;
            };

            updateTimer();
            setInterval(updateTimer, 1000);
        });
    }

    // 打印功能
    const printButtons = document.querySelectorAll('.btn-print');
    printButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            window.print();
        });
    });
});

// 通用函数：格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 通用函数：显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.innerHTML = `
    ${message}
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  `;

    const container = document.querySelector('.notification-container') || document.body;
    container.appendChild(notification);

    // 5秒后自动关闭
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => notification.remove(), 150);
    }, 5000);
}